package pl.pw.mkmw.pnganimator.image;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.InflaterInputStream;

/**
 *
 * @author MK
 */
public class DataDecompressor {

    private static final Logger LOG = Logger.getLogger(DataDecompressor.class.getName());

    public static byte[] decompress(byte[] compressed) {
        LOG.log(Level.FINE, "Decompressing, compressed size : {0}", compressed.length);
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(compressed);

            InflaterInputStream iis = new InflaterInputStream(bais);

            byte[] uncompressed = new byte[compressed.length * 4];
            
            int i = 0;
            //increase memory if necessary
            while (iis.available() == 1) {
                if (i == uncompressed.length) {
                    uncompressed = Arrays.copyOf(uncompressed, (int) Math.floor(1.5 * i));
                }
                uncompressed[i++] = (byte) iis.read();
            }

            byte[] overall = new byte[i - 1];

            System.arraycopy(uncompressed, 0, overall, 0, i - 1);
            LOG.log(Level.FINE, "Decompressing, uncompressed size : {0}", overall.length);
            
            return overall;

        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
            return new byte[0];
        }
    }
}
